﻿using System;
using System.Web.Mvc;
using StructureMap;
using System.Web.Routing;

namespace NMA.Web.Core.ControllerFactory
{
    using NMA.Infrastructure.NHibernate.Container;
    using NMA.Web.Areas.Admin.Controllers;

    /// <summary>
    /// http://joelabrahamsson.com/entry/really-simple-ioc-with-aspnet-mvc-and-structuremap
    /// http://weblogs.asp.net/shijuvarghese/archive/2008/10/10/asp-net-mvc-tip-dependency-injection-with-structuremap.aspx
    /// http://elijahmanor.com/webdevdotnet/post/using-structuremap-with-aspnet-mvc-mvc-contrib.aspx
    /// </summary>
    public class StructureMapControllerFactory : DefaultControllerFactory
    {
        /// <summary>
        /// Referenced to http://stackoverflow.com/questions/1357485/asp-net-mvc2-preview-1-are-there-any-breaking-changes
        /// </summary>
        /// <param name="requestContext"></param>
        /// <param name="controllerType"></param>
        /// <returns></returns>
        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            //Debug.Print("Controller: {0}, Action: {1}", requestContext.RouteData.Values["Controller"], requestContext.RouteData.Values["Action"]);

            if (controllerType == null)
            {
                //Debug.Print("Is IController: {0}", (controllerType is IController));
                //Debug.Print("Is null: {0}", (controllerType == null));
                return null;
            }

            return (IController)IoC.GetInstance(controllerType);
        }
    }
}